import React, { Component } from 'react'
import { withRouter } from "react-router-dom"
import { Card, Button, Select, Input, Table, message, Modal } from 'antd'
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import http from "../../../api"
import "./index.css"

const { Option } = Select
const { confirm } = Modal

class Home extends Component {
  columns = [
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '商品描述',
      dataIndex: 'desc',
      key: 'desc',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      align: 'center',
      width: '100px',
      render: (text) => {
        return '￥' + text
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (status) => {
        return (
          <>
            <Button type="primary" onClick={this.commodityStatus} size="small">{status ? '下架' : '上架'}</Button>
            <span>&nbsp;{status ? '在售' : '不售'}</span>
          </>
        )
      }
    },
    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      align: 'center',
      width: '100px',
      render: () => {
        return (
          <>
            <Button type="link" onClick={this.modifyCommodity}>修改商品</Button>
            <Button type="link" onClick={this.deleteCommodity}>删除商品</Button>
            <Button type="link" onClick={this.seeDetails}>查看详情</Button>
          </>
        )
      }
    }
  ]
  state = { dataSource: [], commodity: {}, keyword: '', choice: 0 }
  componentDidMount() {
    this.getCommodityData()
  }
  getCommodityData = async () => {
    // 获取商品数据
    const { data } = await http.get('/rest/products/whole')
    data.forEach(item => {
      item.key = item._id
    })
    this.setState({ dataSource: data })
  }
  // 上架、下架按钮回调
  commodityStatus = () => {
    setTimeout(() => {
      const { name, status, _id } = this.state.commodity
      // 确认提示框
      confirm({
        title: status ? `确认下架 "${name}" 吗?` : `确认上架 "${name}" 吗?`,
        icon: <ExclamationCircleOutlined />,
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          setTimeout(async () => {
            // 更新商品状态
            const { data } = await http.post('/rest/products/update', { _id, status: !status })
            // 重新获取数据
            this.getCommodityData()
            message.success(data.message)
          })
        }
      })
    })
  }
  // 关键字搜索商品
  search = () => {
    let { dataSource, keyword, choice } = this.state
    if (!(keyword.trim())) return message.error('关键字不能为空')
    let searchArr = []
    if (choice) {
      // 按描述搜索
      searchArr = dataSource.filter(item => {
        return item.desc.indexOf(keyword) !== -1
      })
    } else {
      // 按名称搜索
      searchArr = dataSource.filter(item => {
        return item.name.indexOf(keyword) !== -1
      })
    }
    this.setState({ searchArr })
  }
  // 添加商品跳转路由
  jumpRoute = () => {
    this.props.history.push('/admin/administration/addupdate')
  }
  // 查看商品详情跳转路由
  seeDetails = () => {
    setTimeout(() => {
      const { commodity } = this.state
      this.props.history.push('/admin/administration/detail', { commodity })
    })
  }
  // 修改商品跳转路由
  modifyCommodity = () => {
    setTimeout(() => {
      const { commodity } = this.state
      this.props.history.push('/admin/administration/addupdate', { commodity })
    })
  }
  // 删除商品
  deleteCommodity = () => {
    setTimeout(() => {
      const { _id, name } = this.state.commodity
      // 确认提示框
      confirm({
        title: `确认删除商品 "${name}" 吗?`,
        icon: <ExclamationCircleOutlined />,
        okText: '确定',
        cancelText: '取消',
        onOk: async () => {
          // 删除请求
          const { data } = await http.delete('/rest/products/delete', { params: { _id } })
          // 重新获取数据
          this.getCommodityData()
          message.success(data.message)
        }
      })
    })
  }
  render() {
    const { dataSource, searchArr } = this.state
    const title = (
      <>
        <Select
          defaultValue={0}
          style={{ width: 150, marginRight: 10 }}
          onChange={value => { this.setState({ choice: Number(value) }) }}
        >
          <Option value={0}>按名称搜索</Option>
          <Option value={1}>按描述搜素</Option>
        </Select>
        <Input
          placeholder="关键字"
          onChange={e => { this.setState({ keyword: e.target.value }) }}
          style={{ width: 150, marginRight: 10 }}
        />
        <Button type="primary" onClick={this.search}>搜索</Button>
      </>
    )
    const extra = <Button type="primary" icon={<PlusOutlined />} onClick={this.jumpRoute}>添加商品</Button>
    return (
      <div className="cm-home">
        <Card title={title} extra={extra} style={{ height: '100%' }}>
          <Table
            bordered={true}
            dataSource={searchArr ? searchArr : dataSource}
            columns={this.columns}
            pagination={{
              defaultCurrent: 1,
              defaultPageSize: 5,
              showQuickJumper: true,
              showSizeChanger: false,
              position: ['bottomCenter']
            }}
            onRow={record => {
              return {
                // 点击行
                onClick: () => {
                  // 收集商品信息
                  this.setState({ commodity: record })
                }
              }
            }}
          />
        </Card>
      </div>
    )
  }
}

export default withRouter(Home)
